package com.glx.test.datafluxaispringboot.service;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.glx.test.datafluxaispringboot.model.ChatMessage;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ChatSessionManager {
    private final Cache<String, List<ChatMessage>> contextCache = Caffeine.newBuilder()
            .expireAfterAccess(30, TimeUnit.MINUTES)
            .maximumSize(1000)
            .build();

    public List<ChatMessage> getOrCreateSession(String sessionId) {
        return contextCache.get(sessionId, k ->
                Collections.synchronizedList(new java.util.ArrayList<>())
        );
    }

    public void addMessage(String sessionId, ChatMessage message) {
        List<ChatMessage> messages = getOrCreateSession(sessionId);
        messages.add(message);
        truncateContext(messages);
    }

    private void truncateContext(List<ChatMessage> messages) {
        // 保留最近5轮对话（10条消息）
        int maxSize = 10;
        while (messages.size() > maxSize) {
            messages.remove(0);
        }
    }
} 